<template>
  <div class="login-wrapper">
    <a-card class="login-card">
      <a-form ref="loginFormRef" :model="loginForm" :rules="loginRules" @submit="handleLogin" auto-label-width>
        <a-form-item field="username" label="用户名">
          <a-input v-model="loginForm.username" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item field="password" label="密码">
          <a-input-password v-model="loginForm.password" placeholder="请输入密码" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit" :loading="loginLoading" long style="margin-top: 12px"
            >登录</a-button
          >
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { Message } from '@arco-design/web-vue'
import { LoginAPI } from '@/api/login'
import { useUserStore } from '@/store/modules/user'
import { useRouter } from 'vue-router'
const loginFormRef = ref()
const loginLoading = ref(false)
const userStore = useUserStore()
const router = useRouter()
const homePath = import.meta.env.VITE_APP_BASE_ASSETS
const loginForm = ref({
  username: 'admin',
  password: 'admin123'
})

const loginRules = {
  username: [{ required: true, message: '请输入用户名' }],
  password: [{ required: true, message: '请输入密码' }]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  try {
    loginLoading.value = true
    const valid = await loginFormRef.value.validate()
    if (valid) return

    const { code, data } = await LoginAPI(loginForm.value)
    if (code === 200) {
      userStore.setToken(data.access_token)
      await router.push(homePath)
      Message.success('登录成功！')
    } else {
      Message.error('用户名或密码错误')
    }
  } catch (err) {
    console.log(err)
  } finally {
    loginLoading.value = false
  }
}
</script>

<style scoped>
.login-wrapper {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #45caff 0%, #5c53fe 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-card {
  width: 360px;
  padding: 36px 28px 20px 28px;
  border-radius: 12px;
  box-shadow: 0 6px 32px rgba(0, 0, 0, 0.13);
}
</style>
